package com.swgk.core.view.selectdate;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.swgk.core.R;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author 张驰
 * @date 2021/8/12 11:08
 * @Description 时间自定义选择器
 * @name com.example.bao.calendarlist
 */
public class DatePopupWindow extends PopupWindow implements View.OnClickListener {

    private TextView tv_ok;
    private CalendarList calendarList;
    private TextView tvStartToEndDate;
    private View rootView;
    private Activity activity;
    private String startDesc;
    private String endDesc;
    private boolean isFlage;
    private boolean isClose;
    private DateOnClickListener mOnClickListener = null;


    private DatePopupWindow(Builder builder) {
        this.activity = builder.context;
        this.startDesc = builder.startDesc;
        this.endDesc = builder.endDesc;
        this.isFlage = builder.isFlage;
        this.isClose = builder.isClose;
        this.mOnClickListener = builder.mOnClickListener;

        LayoutInflater inflater = (LayoutInflater) this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        rootView = inflater.inflate(R.layout.popupwindow_hotel_date, null);
        this.setContentView(rootView);
        this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        this.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        this.setAnimationStyle(R.style.dialogWindowAnim);
        this.setFocusable(true);
        this.setTouchable(true);
        this.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        this.setOutsideTouchable(isClose);
        this.setOnDismissListener(new ShareDismissListener());
        backgroundAlpha(activity, 0.5f);

        rootView.findViewById(R.id.btn_close).setOnClickListener(this);
        rootView.findViewById(R.id.view_bg).setOnClickListener(this);
        rootView.findViewById(R.id.btn_clear).setOnClickListener(this);
        rootView.findViewById(R.id.tv_7day).setOnClickListener(this);
        rootView.findViewById(R.id.tv_30day).setOnClickListener(this);
        rootView.findViewById(R.id.tv_90day).setOnClickListener(this);

        tv_ok = rootView.findViewById(R.id.tv_ok);
        tv_ok.setOnClickListener(this);

        tvStartToEndDate = rootView.findViewById(R.id.tv_startToEndDate);
        calendarList = rootView.findViewById(R.id.calendarList);
        calendarList.setIsFlage(isFlage);
        calendarList.setOnDateSelected(new CalendarList.OnDateSelected() {
            @Override
            public void selected(String startDate, String endDate) {
                startDesc = startDate;
                endDesc = endDate;
                tv_ok.setEnabled(true);
                tvStartToEndDate.setText(startDate.replace("-", ".") + "-" + endDate.replace("-", "."));
            }
        });
        create(builder.parentView);
    }

    private void backgroundAlpha(Activity context, float bgAlpha) {
        WindowManager.LayoutParams lp = context.getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        context.getWindow().setAttributes(lp);
    }

    private void create(View view) {
        this.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    /**
     * 弹框显示
     * @param view
     */
    public void showDatePopupWindow(View view,String startTime,String endTime) {
        this.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        backgroundAlpha(activity, 0.5f);
        if (!TextUtils.isEmpty(startTime) && !startTime.equals("0")){
            String start = DateUtils.formatDate(Long.valueOf(startTime),"yyyy-MM-dd");
            String end = start;
            if (!endTime.equals("0")){
                end = DateUtils.formatDate(Long.valueOf(endTime),"yyyy-MM-dd");
            }
            calendarList.setSelectStartToEnd(start,end);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_close || id == R.id.view_bg) {
            if (mOnClickListener != null){
                mOnClickListener.onDismiss();
            }
            dismiss();
        } else if (id == R.id.btn_clear) {
            calendarList.clearState(true);
            startDesc = "";
            endDesc = "";
            tvStartToEndDate.setText("");
        } else if (id == R.id.tv_7day) {
            calendarList.setSelectStartToEnd(getdayTime(Calendar.DATE, -6), getdayTime(Calendar.DATE, 0));
        } else if (id == R.id.tv_30day) {
            calendarList.setSelectStartToEnd(getdayTime(Calendar.MONTH, -1), getdayTime(Calendar.DATE, 0));
        } else if (id == R.id.tv_90day) {
            calendarList.setSelectStartToEnd(getdayTime(Calendar.MONTH, -3), getdayTime(Calendar.DATE, 0));
        } else if (id == R.id.tv_ok) {
            if (TextUtils.isEmpty(startDesc)){
                //MToast.showLongToast(activity,"请选择开始日期之后在点击完成",Gravity.CENTER);
                //return;
                startDesc = "0";
                endDesc = "0";
            }else{
                if (TextUtils.isEmpty(endDesc)){
                    MToast.showLongToast(activity,"请选择日期之后在点击完成",Gravity.CENTER);
                    return;
                }
            }
            if (mOnClickListener != null) {
                mOnClickListener.getDate(startDesc, endDesc);
                try {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    if (startDesc.equals("0") && endDesc.equals("0")){
                        mOnClickListener.getDate(0l,0l);
                    }else{
                        mOnClickListener.getDate(format.parse(startDesc).getTime(),format.parse(endDesc).getTime());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    mOnClickListener.getDate(0l,0l);
                }
                mOnClickListener.onDismiss();
            }
            dismiss();
        }
    }


    /**
     * return startDate、endDate(格式：2012-12-10)
     * 选中完成后返回开始时间和结束时间
     * return startGroupPosition、startChildPosition、endGroupPosition、endChildPosition
     * 返回选中时间区间的状态标记，监听中接收后在builder中setInitSelect()方法中直接传出入（可用于记录上次选中的状态，用户再点击进入的时候恢复上一次的区间选中状态）
     */
    public abstract static class DateOnClickListener {

        public void getDate(String startDate, String endDate){
        }

        public void getDate(Long startDate, Long endDate){
        }


        public  void onDismiss(){
        }
    }

    public static class Builder {
        private String date;
        private Activity context;
        private View parentView;
        private String startDesc;
        private String endDesc;
        private boolean isFlage;
        private boolean isClose;
        private DateOnClickListener mOnClickListener = null;

        /**
         *
         * @param context
         * @param date
         * @param parentView
         */
        @SuppressLint("SimpleDateFormat")
        public Builder(Activity context, Date date, View parentView) {
            this.date = new SimpleDateFormat("yyyy-MM-dd").format(date);
            this.context = context;
            this.parentView = parentView;
            this.startDesc = "开始";
            this.endDesc = "结束";
            this.isFlage = false; //默认不显示
            this.isClose = true; //默认消失
        }

        /**
         *
         * @param context
         * @param date
         * @param parentView
         * @param isFlage 是否显示开始或者结束字样
         * @param isClose 点击外部是否可消失 ，true 消失，false 不消失
         */
        @SuppressLint("SimpleDateFormat")
        public Builder(Activity context, Date date, View parentView,boolean isFlage,boolean isClose) {
            this.date = new SimpleDateFormat("yyyy-MM-dd").format(date);
            this.context = context;
            this.parentView = parentView;
            this.startDesc = "开始";
            this.endDesc = "结束";
            this.isFlage = isFlage;
            this.isClose = isClose;
        }

        public DatePopupWindow builder() {
            return new DatePopupWindow(this);
        }

        public Builder setDateOnClickListener(DateOnClickListener mlListener) {
            mOnClickListener = mlListener;
            return this;
        }
    }

    private class ShareDismissListener implements OnDismissListener {
        @Override
        public void onDismiss() {
            backgroundAlpha(activity, 1f);
        }
    }

    /**
     * 获取从现在起过去或者未来多长时间
     *
     * @param field Calendar.DATE 天 Calendar.MONTH 月
     * @param amout 正数，未来多少天或月；负数，过去多少天或月
     * @return
     */
    private String getdayTime(int field, int amout) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(field, amout);
        Date d = c.getTime();
        return format.format(d);
    }
}
